<template>
  <div>
    <el-drawer
      v-loading="loading"
      :wrapper-closable="false"
      append-to-body
      :title="title"
      :close-on-press-escape="true"
      size="80%"
      :modal="true"
      :visible.sync="isVisible"
      direction="rtl"
      element-loading-text="加载中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 0.8)"
      custom-class="payment-file-drawer"
      @close="close"
    >
      <div class="drawer-content">
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <span class="file-title">{{ paymentFileData.name || '新建支付文件' }}</span>
            <div v-if="paymentFileData.crm_order" class="file-info">
              <span class="info-item">关联订单编号: {{ paymentFileData.crm_order.order_no }}</span>
              <span>订单名称: {{ order_name }}</span>
            </div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="action-buttons">
            <el-button type="primary" round size="mini" :loading="saveLoading" @click="handleSavePaymentFile">保存信息</el-button>
            <el-button v-if="paymentFileData.token" type="success" round size="mini" @click="openExternalLink">查看</el-button>
            <el-dropdown style="margin-left: 10px;" @command="handleFileCommand">
              <el-button type="primary" round size="mini">
                支付文件操作<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="copy">复制当前</el-dropdown-item>
                <el-dropdown-item command="new">新建</el-dropdown-item>
                <el-dropdown-item command="regenerate-token">重新生成链接</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>

        <el-divider>支付文件信息</el-divider>
        <!-- 支付文件基本信息 -->
        <el-form :model="paymentFileData" label-position="right" label-width="120px" style="margin-top: 20px">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="文件名称" prop="name">
                <el-input v-model="paymentFileData.name" placeholder="请输入支付文件名称" @change="saveToCookies" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关联订单" prop="crm_order_no">
                <el-input v-model="paymentFileData.crm_order_no" placeholder="请输入关联订单编号" readonly @change="saveToCookies" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="快捷访问Token">
                <el-input v-model="paymentFileData.token" placeholder="系统自动生成" readonly>
                  <el-button slot="append" icon="el-icon-refresh" @click="generateToken">重新生成</el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 订单信息显示 -->
        <div v-if="paymentFileData.id && paymentFileData.order_params_array && paymentFileData.order_params_array.length > 0" style="margin-top: 20px;">
          <el-divider>订单信息</el-divider>
          <div class="order-info-container">
            <el-row :gutter="20">
              <el-col
                v-for="(paramObj, index) in paymentFileData.order_params_array"
                :key="index"
                :span="8"
                style="margin-bottom: 15px;"
              >
                <div
                  v-for="(value, key) in paramObj"
                  :key="key"
                  class="order-info-item"
                >
                  <label class="order-info-label">{{ key }}:</label>
                  <span class="order-info-value">{{ value || '无' }}</span>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 通用类别参数组件 -->
        <div v-if="paymentFileData.id" style="margin-top: 20px;">
          <CommonCategoryParams
            ref="categoryParams"
            :model-type="'crmpaymentfile'"
            :object-id="paymentFileData.id"
            :visible="isVisible"
            :upload-directory="-1"
            :upload-keyword="'payment_file'"
            :show-a-i="true"
            :show-parameters-by-default="false"
            :default-category-names="paymentFileData.category_names_array"
            @category-created="handleCategoryCreated"
            @category-updated="handleCategoryUpdated"
            @category-deleted="handleCategoryDeleted"
            @default-categories-created="handleDefaultCategoriesCreated"
          />

          <!-- 如果没有类别，提供快速创建按钮 -->
          <div v-if="paymentFileData.category_names_array && paymentFileData.category_names_array.length > 0" style="text-align: center; margin-top: 15px;">
            <el-button type="success" size="small" @click="createDefaultCategoriesNow">
              <i class="el-icon-plus" /> 立即创建默认分类
            </el-button>
          </div>
        </div>

        <!-- 如果还没有保存，显示提示 -->
        <div v-else style="text-align: center; margin-top: 30px;">
          <el-empty description="请先保存支付文件基本信息">
            <el-button type="primary" @click="handleSavePaymentFile">保存支付文件</el-button>
          </el-empty>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { Get, Post, Put } from '@/api/crm/crmpaymentfile'
import CommonCategoryParams from '@/views/crm/elements/commoncategoryparams'
import { ShowProjectAttr } from '@/api/erp/elicink/project'
import Cookies from 'js-cookie'
import qs from 'qs'

export default {
  name: 'CRMPaymentFileDrawer',
  components: { CommonCategoryParams },
  props: {
    order_no: {
      type: [Number, String],
      default: ''
    },
    order_name: {
      type: [Number, String],
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    },
    uploadDirectory: {
      type: Number,
      default: -1
    },
    uploadKeyword: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      title: '支付文件详情',
      paymentFileData: {
        name: '',
        crm_order_no: '',
        token: '',
        order_params: '',
        order_params_array: [],
        category_names: '',
        category_names_array: []
      },
      loading: false,
      saveLoading: false,
      isVisible: false,
      allPaymentFiles: [], // 存储所有相关的支付文件
      defaultCategoryNames: [] // 存储系统默认分类名称列表
    }
  },
  computed: {
    // 移除了默认分类相关的computed属性
  },
  watch: {
    order_no: {
      handler(val) {
        if (val) {
          this.paymentFileData.crm_order_no = val
        }
        console.log('order_no', val)
        if (val && this.isVisible) {
          this.getPaymentFileData()
        }
      },
      immediate: true
    },
    visible: {
      handler(val) {
        this.isVisible = val
        if (val) {
          // 立即显示loading状态
          this.loading = true

          // 延迟一点执行数据加载，让loading状态先显示出来
          setTimeout(() => {
            this.getPaymentFileData()
          }, 100)
        }
      },
      immediate: true
    },
    // 监控支付文件名称变化，保存到cookies
    'paymentFileData.name': function(val) {
      this.saveToCookies()
    }
  },
  created() {
    // 首先获取系统默认分类
    this.handleGetDefaultCategoryNames()

    if (this.order_no && this.isVisible) {
      this.getPaymentFileData()
    } else {
      // 如果没有order_no，尝试从cookies恢复用户数据
      this.restoreFromCookies()
      this.generateToken()
      // 如果有订单号但没有设置文件名，则设置默认文件名
      if (this.order_no && !this.paymentFileData.name) {
        this.paymentFileData.name = this.order_no + '支付审核文件'
      }
    }
  },
  mounted() {
    // 组件挂载后尝试从cookies中恢复数据
    this.restoreFromCookies()
  },
  methods: {
    // 保存用户输入到cookies
    saveToCookies() {
      const cookieData = {
        name: this.paymentFileData.name,
        category_names_array: this.paymentFileData.category_names_array
      }

      Cookies.set('payment_file_user_data', JSON.stringify(cookieData), { expires: 30 })
      console.log('已保存支付文件数据到cookies:', cookieData)
    },

    // 从cookies恢复用户输入
    restoreFromCookies() {
      try {
        const cookieData = Cookies.get('payment_file_user_data')
        if (cookieData) {
          const userData = JSON.parse(cookieData)
          console.log('从cookies恢复支付文件数据:', userData)

          // 只有在创建新的支付文件时才应用cookie中的数据
          if (!this.paymentFileData.id) {
            if (userData.name) {
              this.paymentFileData.name = userData.name
            }
            if (userData.category_names_array) {
              this.paymentFileData.category_names_array = userData.category_names_array
            }
          }
        }

        // 如果没有用户自定义分类且有系统默认分类，则使用系统默认分类
        if ((!this.paymentFileData.category_names_array || this.paymentFileData.category_names_array.length === 0) && this.defaultCategoryNames.length > 0) {
          this.paymentFileData.category_names_array = [...this.defaultCategoryNames]
          console.log('使用系统默认分类:', this.defaultCategoryNames)
        }
      } catch (error) {
        console.error('恢复支付文件数据失败:', error)
      }
    },

    // 获取支付审核文件默认分类名称列表
    handleGetDefaultCategoryNames() {
      ShowProjectAttr(null, qs.stringify({ name: '支付审核文件_分类' })).then(response => {
        this.defaultCategoryNames = response.data || []
        console.log('获取到系统默认分类:', this.defaultCategoryNames)

        // 如果当前没有设置分类且有系统默认分类，则自动设置
        if ((!this.paymentFileData.category_names_array || this.paymentFileData.category_names_array.length === 0) && this.defaultCategoryNames.length > 0) {
          this.paymentFileData.category_names_array = [...this.defaultCategoryNames]
          console.log('自动设置系统默认分类')
        }
      }).catch(err => {
        console.error('获取默认分类失败:', err)
        // 如果获取失败，使用备用默认分类
        this.defaultCategoryNames = ['收款信息', '付款凭证', '发票资料', '财务对账']
        console.log('使用备用默认分类:', this.defaultCategoryNames)
      })
    },

    // 获取支付文件数据
    getPaymentFileData() {
      if (!this.order_no) {
        console.log('没有订单编号，跳过获取支付文件数据')
        // 当没有订单数据时，是新建状态，此时尝试从cookies恢复用户数据
        this.restoreFromCookies()
        this.generateToken() // 为新文件生成token
        // 如果有订单号但没有设置文件名，则设置默认文件名
        if (this.order_no && !this.paymentFileData.name) {
          this.paymentFileData.name = this.order_no + '支付审核文件'
        }
        this.loading = false
        return
      }

      this.loading = true
      console.log('获取支付文件数据，订单编号:', this.order_no)

      // 通过订单号查询支付文件
      Get(null, qs.stringify({ order_no: this.order_no })).then(response => {
        console.log('获取到支付文件数据:', response.data)

        if (response.data && response.data.data && response.data.data.length > 0) {
          // 保存所有相关支付文件数据
          this.allPaymentFiles = [...response.data.data]

          // 使用第一个支付文件数据
          const tempData = JSON.parse(JSON.stringify(this.allPaymentFiles[0]))
          this.title = `支付文件详情: ${tempData.name || '未命名'}`

          // 处理category_names字段
          if (tempData.category_names) {
            try {
              tempData.category_names_array = JSON.parse(tempData.category_names)
            } catch (e) {
              tempData.category_names_array = tempData.category_names.split(',').filter(name => name.trim())
            }
          } else {
            tempData.category_names_array = []
          }

          // 处理关联订单显示
          if (tempData.crm_order && tempData.crm_order.order_no) {
            tempData.crm_order_no = tempData.crm_order.order_no
          }

          // 处理order_params字段，确保order_params_array存在
          if (tempData.order_params) {
            console.log('原始order_params数据:', tempData.order_params)

            // 尝试解析为JSON数组
            if (typeof tempData.order_params === 'string') {
              try {
                tempData.order_params_array = JSON.parse(tempData.order_params)
              } catch (e) {
                console.error('解析order_params失败:', e)
                tempData.order_params_array = []
              }
            } else if (Array.isArray(tempData.order_params)) {
              tempData.order_params_array = tempData.order_params
            } else {
              tempData.order_params_array = []
            }
          } else {
            tempData.order_params_array = []
          }

          console.log('处理后的order_params_array:', tempData.order_params_array)

          this.paymentFileData = tempData

          // 如果支付文件存在但没有预定义分类，且系统有默认分类，则自动设置
          if ((!this.paymentFileData.category_names_array || this.paymentFileData.category_names_array.length === 0) && this.defaultCategoryNames.length > 0) {
            this.paymentFileData.category_names_array = [...this.defaultCategoryNames]
            console.log('为现有支付文件自动应用系统默认分类:', this.defaultCategoryNames)
          }

          this.loading = false
        } else {
          console.log('没有找到匹配的支付文件数据，创建新的支付文件')
          this.paymentFileData = {
            name: this.order_no + '支付审核文件',
            crm_order_no: this.order_no,
            token: '',
            order_params: '',
            order_params_array: [],
            category_names: '',
            category_names_array: []
          }
          this.title = '新建支付文件'
          this.restoreFromCookies()
          this.generateToken()
          this.loading = false
        }
      }).catch(error => {
        console.error('获取支付文件数据失败', error)
        this.loading = false
        this.$notify.error({
          title: '错误',
          message: '获取支付文件数据失败: ' + (error.message || '未知错误')
        })

        // 创建一个新的空支付文件对象
        this.paymentFileData = {
          name: this.order_no + '支付审核文件',
          crm_order_no: this.order_no,
          token: '',
          order_params: '',
          order_params_array: [],
          category_names: '',
          category_names_array: []
        }
        this.restoreFromCookies()
        this.generateToken()
        this.title = '新建支付文件'
      })
    },

    // 保存支付文件
    handleSavePaymentFile() {
      if (!this.paymentFileData.name || !this.paymentFileData.name.trim()) {
        this.$message.warning('请输入支付文件名称')
        return
      }

      if (!this.paymentFileData.crm_order_no) {
        this.$message.warning('缺少关联订单信息')
        return
      }

      this.loading = true
      this.saveLoading = true

      // 构建要保存的数据对象
      const saveData = { ...this.paymentFileData }

      // 处理category_names字段
      if (saveData.category_names_array && saveData.category_names_array.length > 0) {
        saveData.category_names = JSON.stringify(saveData.category_names_array)
      }

      delete saveData.category_names_array

      // 确定是更新还是新建
      const isUpdate = !!saveData.id

      const saveOrUpdatePaymentFile = () => {
        if (isUpdate) {
          return Put(saveData.id, saveData)
        } else {
          return Post(saveData)
        }
      }

      saveOrUpdatePaymentFile()
        .then(response => {
          const savedPaymentFile = response.data.data
          console.log('支付文件保存/更新成功:', savedPaymentFile)

          // 如果是新创建的，更新ID
          if (!isUpdate) {
            this.paymentFileData.id = savedPaymentFile.id
          }

          this.$notify({
            title: '成功',
            message: '支付文件保存成功',
            type: 'success',
            duration: 2000
          })

          // 如果有预定义分类，自动创建分类
          if (this.paymentFileData.category_names_array && this.paymentFileData.category_names_array.length > 0) {
            setTimeout(() => {
              if (this.$refs.categoryParams && this.$refs.categoryParams.createDefaultCategories) {
                this.$refs.categoryParams.createDefaultCategories()
                console.log('正在创建默认分类:', this.paymentFileData.category_names_array)
              }
            }, 500)
          }

          this.saveLoading = false
          this.loading = false
        })
        .catch(error => {
          console.error('保存支付文件失败', error)
          this.loading = false
          this.saveLoading = false
          this.$notify.error({
            title: '错误',
            message: '保存支付文件失败: ' + (error.message || '未知错误')
          })
        })
    },

    // 生成Token
    generateToken() {
      this.paymentFileData.token = 'pf_' + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
    },

    // 获取支付文件URL
    getPaymentFileUrl() {
      if (!this.paymentFileData.token) return ''
      return `https://v.lianf.com/paymentfileview/${this.paymentFileData.token}`
    },

    // 复制支付文件链接
    copyPaymentFileUrl() {
      const url = this.getPaymentFileUrl()
      if (!url) {
        this.$message.warning('请先生成Token')
        return
      }

      // 复制到剪贴板
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(url).then(() => {
          this.$message.success('支付文件链接已复制到剪贴板')
        })
      } else {
        // 备用方案
        const textArea = document.createElement('textarea')
        textArea.value = url
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        try {
          document.execCommand('copy')
          this.$message.success('支付文件链接已复制到剪贴板')
        } catch (err) {
          this.$message.error('复制失败，请手动复制：' + url)
        }
        document.body.removeChild(textArea)
      }
    },

    // 打开外部链接
    openExternalLink() {
      if (!this.paymentFileData.token) {
        this.$message.warning('请先生成Token')
        return
      }
      const url = this.getPaymentFileUrl()
      window.open(url, '_blank')
    },

    // 处理分类名称变化
    handleCategoryNamesChange(value) {
      this.paymentFileData.category_names_array = value.split(',').map(name => name.trim()).filter(name => name)
    },

    // 处理文件操作命令
    handleFileCommand(command) {
      if (command === 'copy') {
        this.copyPaymentFile()
      } else if (command === 'new') {
        this.createNewPaymentFile()
      } else if (command === 'regenerate-token') {
        this.regenerateToken()
      }
    },

    // 复制支付文件
    copyPaymentFile() {
      if (!this.paymentFileData.id) {
        this.$message.warning('请先保存当前支付文件再进行复制')
        return
      }

      this.$confirm('确认复制当前支付文件？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 复制当前数据
        const copyData = { ...this.paymentFileData }
        delete copyData.id

        // 修改名称和token
        const now = new Date()
        const timeStr = now.getFullYear() +
                      ('0' + (now.getMonth() + 1)).slice(-2) +
                      ('0' + now.getDate()).slice(-2) +
                      ('0' + now.getHours()).slice(-2) +
                      ('0' + now.getMinutes()).slice(-2)
        copyData.name = `${copyData.name || '未命名'}-复制-${timeStr}`
        copyData.token = 'pf_' + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)

        // 处理category_names字段
        if (copyData.category_names_array && copyData.category_names_array.length > 0) {
          copyData.category_names = JSON.stringify(copyData.category_names_array)
        }
        delete copyData.category_names_array

        this.loading = true
        Post(copyData).then(response => {
          this.$notify({
            title: '成功',
            message: '支付文件复制成功',
            type: 'success',
            duration: 2000
          })

          // 切换到新复制的文件
          const newFile = response.data.data
          this.paymentFileData = { ...newFile }
          if (this.paymentFileData.category_names) {
            try {
              this.paymentFileData.category_names_array = JSON.parse(this.paymentFileData.category_names)
            } catch (e) {
              this.paymentFileData.category_names_array = []
            }
          }

          this.title = `支付文件详情: ${this.paymentFileData.name}`
          this.loading = false
        }).catch(error => {
          console.error('复制支付文件失败', error)
          this.loading = false
          this.$notify.error({
            title: '错误',
            message: '复制支付文件失败: ' + (error.message || '未知错误')
          })
        })
      })
    },

    // 创建新支付文件
    createNewPaymentFile() {
      this.$confirm('确定要创建新的支付文件？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 重置数据
        this.paymentFileData = {
          name: this.order_no + '支付审核文件',
          crm_order_no: this.order_no,
          token: '',
          category_names: '',
          category_names_array: []
        }

        this.title = '新建支付文件'
        this.restoreFromCookies()
        this.generateToken()

        this.$notify({
          title: '成功',
          message: '已创建新的支付文件，请填写信息并保存',
          type: 'success',
          duration: 2000
        })
      })
    },

    // 重新生成Token
    regenerateToken() {
      this.$confirm('确认重新生成访问链接？原链接将失效。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.generateToken()
        this.$message.success('访问链接已重新生成')
      })
    },

    // 关闭抽屉
    close() {
      this.$emit('close')
    },

    // 类别参数组件事件处理
    handleCategoryCreated(category) {
      console.log('类别已创建:', category)
    },

    handleCategoryUpdated(category) {
      console.log('类别已更新:', category)
    },

    handleCategoryDeleted(category) {
      console.log('类别已删除:', category)
    },

    handleDefaultCategoriesCreated(categories) {
      console.log('默认类别已创建:', categories)
      this.$message.success(`已创建 ${categories.length} 个默认分类`)
    },

    // 获取占位符文本
    getPlaceholderText() {
      if (this.defaultCategoryNames.length > 0) {
        return `请输入预定义分类名称，用逗号分隔。系统默认分类：${this.defaultCategoryNames.join(', ')}`
      } else {
        return '请输入预定义分类名称，用逗号分隔，如：收款信息,付款凭证,发票资料'
      }
    },

    // 使用系统默认分类
    useDefaultCategories() {
      if (this.defaultCategoryNames.length > 0) {
        this.paymentFileData.category_names_array = [...this.defaultCategoryNames]
        this.saveToCookies()
        this.$message.success('已应用系统默认分类')
      }
    },

    // 立即创建默认分类
    createDefaultCategoriesNow() {
      if (this.$refs.categoryParams && this.$refs.categoryParams.createDefaultCategories) {
        this.$refs.categoryParams.createDefaultCategories()
        this.$message.success('正在创建默认分类...')
      } else {
        this.$message.warning('分类组件尚未加载完成，请稍后再试')
      }
    }
  }
}
</script>

<style scoped>
/* 抽屉内容区域样式 */
.el-drawer >>> .el-drawer__body {
  padding: 0;
}

.el-drawer >>> .el-drawer__header {
  margin-bottom: 0;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.drawer-content {
  padding: 20px;
  background-color: #fff;
}

.file-title {
  display: inline-block;
  font-size: 20px;
  font-weight: 600;
  margin-right: 10px;
  color: #303133;
}

.file-info {
  display: block;
  margin-top: 8px;
  color: #606266;
  font-size: 14px;
}

.info-item {
  margin-right: 15px;
}

.action-buttons {
  text-align: right;
  padding-top: 5px;
}

@media (max-width: 992px) {
  .action-buttons {
    text-align: left;
    margin-top: 15px;
  }
}

/* 优化表单样式 */
.el-form-item {
  margin-bottom: 22px;
}

.el-form-item >>> .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.el-form-item >>> .el-input__inner {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.3s;
}

.el-form-item >>> .el-input__inner:hover {
  border-color: #c0c4cc;
}

.el-form-item >>> .el-input__inner:focus {
  border-color: #409EFF;
}

/* 分隔线样式 */
.el-divider {
  margin: 24px 0;
}

.el-divider >>> .el-divider__text {
  background-color: #f5f7fa;
  color: #409EFF;
  font-weight: bold;
  padding: 0 20px;
}

/* 美化表单样式 */
.el-form {
  background-color: #f9fafc;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 按钮样式优化 */
.el-button {
  margin-left: 10px;
}

.el-button:first-child {
  margin-left: 0;
}

/* 抽屉全局样式 */
.payment-file-drawer >>> .el-drawer__header {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.el-dropdown {
  display: inline-block;
}

/* 在小屏幕下优化下拉菜单显示 */
@media (max-width: 768px) {
  .el-dropdown {
    display: block;
    margin-top: 10px;
  }
}

/* 订单信息显示样式 */
.order-info-container {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 20px;
  margin-bottom: 20px;
}

.order-info-item {
  margin-bottom: 10px;
}

.order-info-label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
  min-width: 80px;
  display: inline-block;
}

.order-info-value {
  color: #303133;
  font-weight: 400;
}
</style>
